package com.yyx.controller;

import com.yyx.pojo.dto.PackageDto;
import com.yyx.pojo.entity.Package;
import com.yyx.pojo.request.package_.PackageUpdateRequest;
import com.yyx.service.PackageService;
import com.yyx.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/package")
public class PackageController {

    @Autowired
    private PackageService packageService;

    @GetMapping
    public ResponseMessage<Page<Package>> list(@RequestParam(defaultValue = "0") int page,
                                               @RequestParam(defaultValue = "20") int size) {
        Page<Package> packagePage = packageService.list(page, size);
        return ResponseMessage.success(packagePage);
    }

    @GetMapping("/{id}")
    public ResponseMessage<PackageDto> getById(@PathVariable Long id) {
        return ResponseMessage.success(packageService.getById(id).convert2Dto());
    }

    @GetMapping("/search")
    public ResponseMessage<Page<Package>> search(@RequestParam("q") String query) {
        Page<Package> packagePage = packageService.searchByFileName(query);
        return ResponseMessage.success(packagePage);
    }

    @PostMapping("/upload")
    public ResponseMessage<PackageDto> upload(@RequestParam("file") MultipartFile file,
                                              @RequestParam("version") String version,
                                              @RequestParam("officialUrl") String officialUrl) throws IOException {
        return ResponseMessage.success(packageService.save(file, version, officialUrl).convert2Dto());
    }

    @PutMapping
    public ResponseMessage<PackageDto> update(@RequestBody PackageUpdateRequest request) {
        return ResponseMessage.success(packageService.update(request).convert2Dto());
    }

    @DeleteMapping("/{id}")
    public ResponseMessage<?> delete(@PathVariable Long id) {
        packageService.delete(id);
        return ResponseMessage.success(null);
    }
}